//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by David on 15/11/25.
//  Copyright © 2015年 DV. All rights reserved.
//

import UIKit
import ReactiveCocoa
class UserAccountViewModel: NSObject {
    static let sharedTools = UserAccountViewModel()
    //初始化时,就读取用户信息
    override init() {
        useraccount = UserAccount.loadAccount()
    }
    var useraccount:UserAccount?
    
    //question:加了 "="就不能访问本类属性?
    var avatarURL : NSURL?  {
//        let url = NSURL(string: usera ?? "")
        return NSURL(string: useraccount?.avatar_large ?? "")
    }

     func loadUserInfo(code:String)->RACSignal{
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            NetworkingTools.sharedTools.loadAccessToken(code).subscribeNext({ (result) -> Void in
                //成功获得accesstoken 和uid
                //通过accesstoken和uid 获取用户数据列表
                let account = UserAccount(dict:result as! [String : AnyObject])
                self.useraccount = account
                NetworkingTools.sharedTools.loadUserInfo(account.access_token, uid: account.uid).subscribeNext({ (result) -> Void in
                    //获得用户信息 建立用户模型
                    account.avatar_large = result["avatar_large"]as?String
                    account.name = result["name"]as?String
                    account.saveAccount()
                    subscriber.sendCompleted()
                    }, error: { (error) -> Void in
                        subscriber.sendError(error)
                        print(error)
                })
                }, error: { (error) -> Void in
                    print(error)
            })

            
            
            
            return nil
        })
    }
    
}
